package org.cubeland.game.preload {	
	import org.papervision3d.objects.DisplayObject3D;
	import caurina.transitions.Tweener;
	import org.cubeland.game.core.drawing.DrawText3D;
	import flash.events.Event;
	import org.cubeland.game.core.drawing.DrawGame;
	import org.cubeland.game.core.drawing.DrawYuki;
	/**
	 * CubeLand.org Game
	 * @author Duarte Peixinho
	 */
	public class Preload extends DrawGame
	{
		
		public var yuki:DrawYuki;
		public var labelGame:DrawText3D;
		private var dummy:DisplayObject3D;
		private var _arrived:Boolean = false;
		private var n:uint;
		public function Preload() 
		{
			// instanciate 3D Engine
			super();
			// init 3D Engine
			init();
					
			_viewport.y=-50;		
			// set dummy object
			dummy = new DisplayObject3D();
			_scene.addChild(dummy);			
			// draw yuki
			yuki = new DrawYuki(_viewport);
			yuki.x=-1000;
			yuki.z=-1000;
			Tweener.addTween(yuki,{ time:5,x:-50,transition:"linear",onComplete:yukiArrived });
			yuki.rotationY = -150;
			yuki.walk();
			// code
			_scene.addChild(yuki);
			
			labelGame = new DrawText3D("game developed by");
			labelGame.z=-300;
			labelGame.y=100;
			
			labelGame.lookAt(_camera);
			labelGame.rotationY +=180;
			_scene.addChild(labelGame);
					
			_camera.moveUp(100);
			_camera.moveBackward(500);
			_camera.moveRight(1000);
									
			// add loop event
			addEventListener(Event.ENTER_FRAME, loop);
		}		
		
		private function loop(e:Event):void {
			//yuki.rotationY = Math.atan2(_viewport.containerSprite.mouseY, _viewport.containerSprite.mouseX) * 180/Math.PI-90;
			yuki.update();
			labelGame.lookAt(_camera);
			labelGame.rotationY +=180;							
			dummy.x = (labelGame.x - yuki.x) / 2;
			dummy.y = (labelGame.y - yuki.y) / 2;
			dummy.z = -500;
			_camera.lookAt(dummy);	
			
											
			render();
		}
		
		private function yukiArrived():void {			
			yuki.stop();
			//yuki.rotationY = -75;
			Tweener.addTween(yuki, {rotationY:-60,time:1 });
			Tweener.addTween(_camera,{time:5,x:500});
			_arrived=true;
			lookSomeWhere();
		}
		private function lookSomeWhere():void {
			var oldN:uint=n;
			do{n=Math.round(Math.random() * 3 +1);}while(n == oldN);
			switch(n) {
				case 1: 
					yuki.lookLeft();
				break;
				case 2: 
					yuki.lookRight();
				break;
				case 3: 
					yuki.lookCenter();
				break;
				case 4: 
					yuki.lookUp();
				break;
			}
			Tweener.addTween(yuki, { time:2, onComplete:lookSomeWhere});
			
		}
	}

}